<?php
namespace ChannelThrift\Processor;

use \Common\Org\PhpRedis;
use \Services\BailService\BailServiceIf;
use \Services\BailService\InvalidException;
use \Services\BailService\Bail;
use \ChannelThrift\Service\CarDealerService;
use \ChannelThrift\Service\OrderService;
use \ChannelThrift\Service\DealerBailLogService;
use \ChannelThrift\Service\BailCacheService;

class BailService implements BailServiceIf
{

    private $redis;
    private $exceptionCode = array();

    public function __construct()
    {
        $this->redis = new PhpRedis();
        $this->exceptionCode = C('BAIL_EXCEPTION_CODE')  + C('EXCEPTION_CODE');
    }

    /*
     * 查询保证金
     */
    public function getDealerBail($dealerId)
    {
        $bcs = new BailCacheService();        
        $dealer = $bcs->getDealerBail($dealerId);

        $bail = new Bail();
        $bail->code ='000000';
        $bail->message='success';
        $bail->data = array('bail_amount'=>$dealer['bail_amount'],'dealer_id'=>$dealerId,'freeze_amount'=>$dealer['freeze_amount'],'indemnity_amount'=>$dealer['indemnity_amount'],'minus_amount'=>$dealer['minus_amount']);
        return $bail;
    }

    /**冻结保证金
     * @param int $dealerId   车商ID
     * @param float $amount   冻结金额
     * @param int $orderId    订单ID
     * @return Bail
     * @throws InvalidException
     */
    public function freezeBail($dealerId, $amount, $orderId)
    {
        $bcs = new BailCacheService();        
        $freezeInfo = $bcs->getFreezeLogInfo($orderId,$dealerId);               
        if ($freezeInfo) {
            $dealer = $bcs->getDealerBail($dealerId); 
            $bail = new Bail();
            $bail->code ='000000';
            $bail->message='success';
            $bail->data = array('bail_amount'=>$dealer['bail_amount'],'dealer_id'=>$dealerId,'freeze_amount'=>$dealer['freeze_amount'],'indemnity_amount'=>$dealer['indemnity_amount'],'minus_amount'=>$dealer['minus_amount']);
            return $bail;
        }

        $dealerObj = new CarDealerService();
        $dealer = $dealerObj->getCarDealer($dealerId);
        if (empty($dealer)) {
            /* 没有这个车商 */
            $trace_str = "order_id:".$orderId." dealer_id:".$dealerId." code:10001 msg:".$this->exceptionCode[10001];
            trace($trace_str,'','ERR',true);
            throw new InvalidException(array('code' => 10001, 'message' => $this->exceptionCode[10001]));
        }
        if ($dealer['status'] != 1) {
            /* 用户没有开通拍卖 */
            $trace_str = "order_id:".$orderId." dealer_id:".$dealerId." code:10002 msg:".$this->exceptionCode[10002];
            trace($trace_str,'','ERR',true);
            throw new InvalidException(array('code' => 10002, 'message' => $this->exceptionCode[10002]));
        }
	    $orderObj = new OrderService();
        $order = $orderObj->getOrder($orderId);
        /**可冻结的拍单状态**/
        $type = array(3,4); //3 投标，4 竞标
        if ( !in_array($order['status'],$type)) {
            /* 该车没有正在拍卖 */
            $trace_str = "order_id:".$orderId." dealer_id:".$dealerId." code:10004 msg:".$this->exceptionCode[10004];
            trace($trace_str,'','ERR',true);
            throw new InvalidException(array('code' => 10004, 'message' => $this->exceptionCode[10004]));
        }

        if (empty($order)) {
            /* 无效的订单 */
            $trace_str = "order_id:".$orderId." dealer_id:".$dealerId." code:10003 msg:".$this->exceptionCode[10003];
            trace($trace_str,'','ERR',true);
            throw new InvalidException(array('code' => 10003, 'message' => $this->exceptionCode[10003]));
        }
        
        $bcs = new BailCacheService();
        $use_type = 2;
        $info = array();
        $info['dealer_id']=$dealerId;        
        $info['order_id']=$orderId;        
        $info['use_type']=2;        
        $info['occur_money'] = $amount;
        $queueLen = $bcs->bailChangePushQueue($use_type,$info);
        $dealer = $bcs->getDealerBail($dealerId);


        $bail = new Bail();
        $bail->code ='000000';
        $bail->message='success';
        $bail->data = array('bail_amount'=>$dealer['bail_amount'],'dealer_id'=>$dealerId,'freeze_amount'=>$dealer['freeze_amount'],'indemnity_amount'=>$dealer['indemnity_amount'],'minus_amount'=>$dealer['minus_amount']);
        return $bail;
    }

    /**解冻保证金
     * @param string $dealerIds   车商ID 
     * @param int $orderId    订单ID
     * @return Bail
     * @throws InvalidException
     */
    public function unfreezeBail($dealerIds, $orderId)
    {
        if(empty($dealerIds)){
            trace('车商IDs:'.var_export($dealerIds,true),'','ERR',true);
            throw new InvalidException(array('code' => 10015, 'message' => $this->exceptionCode[10015]));
        }

        $bcs = new BailCacheService();    
        $dealerIds  = explode(',',$dealerIds);         
        foreach ($dealerIds as $dealerId){
            try{
                $use_type = 3;
                $info = array();
                $info['dealer_id']=$dealerId;        
                $info['order_id']=$orderId;        
                $info['use_type']=3;        
                //\Think\Log::write(var_export($info,true));
                $queueLen = $bcs->bailChangePushQueue($use_type,$info);                
            }catch(InvalidException $e){
                if ($e->getCode()==500053){                    
                    continue;
                }
                throw new $e;
            }
        }
        $bail = new Bail();
        $bail->code ='000000';
        $bail->message='success';
        return $bail;
    }

    /**减少保证金
     * @param int $dealerId   车商ID
     * @param float $amount   金额
     * @param int $useType    使用类型
     * @param string $useDetail   使用备注
     * @param int $rechargeMethod    扣除方式
     * @param int $payMentId     付款单ID  //$payMethodId
     * @param int $collectionId   收款单ID
     * @return Bail
     * @throws InvalidException
     */
    public function decBail($dealerId, $amount, $useType, $useDetail,$orderId=0,$rechargeMethod=0,$payMentId=0,$collectionId=0)
    {

        $typs = array(4,5,6,8);
        if(!in_array($useType,$typs)){
            /* 类型不存在或类型错误 */
            throw new InvalidException(array('code' => 500057, 'message' => $this->exceptionCode[500057]));
        }

        $bcs = new BailCacheService();        
        $use_type = $useType;
        $info = array();
        $info['dealer_id']=$dealerId;        
        $info['order_id']=$orderId;        
        $info['use_type']=$useType;   
        $info['use_detail'] =  $useDetail;     
        $info['occur_money'] = $amount;
        $info['recharge_method'] =  $rechargeMethod;
        $info['payment_id'] =  $payMentId;
        $info['collection_id'] =  $collectionId;
        $queueLen = $bcs->bailChangePushQueue($use_type,$info);
        $dealer = $bcs->getDealerBail($dealerId);

        $bail = new Bail();
        $bail->code ='000000';
        $bail->message='success';
        $bail->data = array('bail_amount'=>$dealer['bail_amount'],'dealer_id'=>$dealerId,'freeze_amount'=>$dealer['freeze_amount'],'indemnity_amount'=>$dealer['indemnity_amount'],'minus_amount'=>$dealer['minus_amount']);
        return $bail;
    }

    /** 增加保证金
     * @param int $dealerId   车商ID
     * @param float $amount  增加金额
     * @param string $useDetail  记录描述
     * @param string $rechargeNo 充值单号
     * @param int $rechargeId  充值订单ID
     * @param int $rechargeMethod  充值方式1支付宝 2拉卡拉 3线下充值 4网银 5代金券
     * @param int $collectionId  收款单ID
     * @return Bail
     * @throws InvalidException
     */
    public function incBail($dealerId, $amount, $useDetail, $rechargeNo, $rechargeId, $rechargeMethod,$collectionId)
    {

        $bcs = new BailCacheService();        
        $use_type = 1;
        $info = array();
        $info['dealer_id']=$dealerId;        
        $info['use_type']=1;        
        $info['occur_money']=$amount;
        $info['use_detail']=$useDetail;
        $info['recharge_method']=$rechargeMethod;
        $info['recharge_no']=$rechargeNo;
        $info['recharge_id']=$rechargeId;
        $info['collection_id']=$collectionId;
        $queueLen = $bcs->bailChangePushQueue($use_type,$info);
        $dealer = $bcs->getDealerBail($dealerId);

        $bail = new Bail();
        $bail->code ='000000';
        $bail->message='success';
        $bail->data = array('bail_amount'=>$dealer['bail_amount'],'dealer_id'=>$dealerId,'freeze_amount'=>$dealer['freeze_amount'],'indemnity_amount'=>$dealer['indemnity_amount'],'minus_amount'=>$dealer['minus_amount']);
        return $bail;
    }

    /** 解冻扣除保证金
     * @param int $dealerId   车商ID
     * @param int $orderId    订单ID
     * @param float $amount     增加金额
     * @param float $decAmonut  扣除金额
     * @param int $useType    使用类型
     * @param string $useDetail  使用详情
     * @return Bail
     * @throws InvalidException
     */
    public function unfreezeDecBail($dealerId , $orderId , $decAmonut, $useType, $useDetail)
    {

        $bcs = new BailCacheService();        
        $freezeInfo = $bcs->getFreezeLogInfo($orderId,$dealerId);
        $dealer = $bcs->getDealerBail($dealerId);        
        if (!$freezeInfo) {
            //未发现冻结
            throw new InvalidException(array('code' => 10009, 'message' => $this->exceptionCode[10009]));
        }
        if ($dealer['freeze_amount']< $decAmonut || $freezeInfo['occur_money'] < $decAmonut) {
            //冻结不足扣除
            throw new InvalidException(array('code' => 10013, 'message' => $this->exceptionCode[10013]));
        }

        $orderObj = new OrderService();
        $orderInfo = $orderObj->getOrder($orderId);
        //扣除保证金
        $info = array();
        $info['dealer_id']=$dealerId;
        $info['order_id']=$orderId;
        $info['use_type']=5;
        $info['use_detail'] = "违约扣款，扣除违约保证金，拍品【".$orderInfo['order_no']."，".$orderId."】。"; 
        $info['occur_money'] = $decAmonut;
        $info['recharge_method'] =  0;
        $info['payment_id'] =  0;
        $info['collection_id'] =  0;
        $queueLen = $bcs->bailChangePushQueue(5,$info);        

        //解冻剩余                
        $info = array();
        $info['dealer_id']=$dealerId;        
        $info['order_id']=$orderId;        
        $info['use_type']=3;
        $info['occur_money']= ($freezeInfo['occur_money']-$decAmonut);   //计算扣除后解冻的金额     
        $info['use_detail'] = "违约扣款，解冻保证金，拍品【".$orderInfo['order_no']."，".$orderId."】。"; //指定信息   
        $queueLen = $bcs->bailChangePushQueue(3,$info);

        $dealer = $bcs->getDealerBail($dealerId);
        $bail = new Bail();
        $bail->code ='000000';
        $bail->message='success';
        $bail->data = array('bail_amount'=>$dealer['bail_amount'],'dealer_id'=>$dealerId,'freeze_amount'=>$dealer['freeze_amount'],'indemnity_amount'=>$dealer['indemnity_amount'],'minus_amount'=>$dealer['minus_amount']);
        return $bail;
    }

    /**获取车商保证金使用记录
     * @param int $dealerId   车商ID
     * @param int $useType    使用类型
     * @param string $useTime  时间
     * @param int $page        页数
     * @param int $pageSize    每页显示数量
     * @param int $isUnFree    只显示冻结
     * @param int $payMethod   支付方式
     * @return Bail
     * @throws InvalidException
     */
    public function getBailLogsByDealerId($dealerId, $useType, $useTime, $page, $pageSize, $isUnFree=0,$payMethod)
    {
        $cdsObj = new CarDealerService();
        $dealer = $cdsObj->getCarDealer($dealerId);
        if (empty($dealer)) {
            /* 没有这个车商 */
            throw new InvalidException(array('code' => 10001, 'message' => $this->exceptionCode[10001]));
        }
        /*拼凑查询条件*/
        $where = " dealer_id = ".$dealerId;
        /* 使用类型 */
        if(!empty($useType)){
            $where .=  " and use_type =".$useType;
        }

        /* 时间 */
        if(!empty($useTime)){
            $isTime = strtotime($useTime);
            if($isTime == false){
                throw new InvalidException(array('code' => 10016, 'message' => $this->exceptionCode[10016]));
            }
            $maxUseTime  = $useTime.' 23:59:59';
            $minUseTime  = $useTime.' 00:00:00';
            $where .= " and createtime between '".$minUseTime."' and '".$maxUseTime."'";
        }
        /* 支付类型 */
        if(!empty($payMethod)){
            $where .= " and recharge_method=".$payMethod;
        }
        /* 是否解冻 */
        if(in_array($isUnFree,array(0,1,2,3,4,5,6,7)) && $isUnFree !== NULL){
          $where .= " and is_free = ".$isUnFree;
        }

        /*默认分页*/
        if(empty($page)){
            $page = 1;
        }
        /*默认显示条数*/
        if(empty($pageSize)){
            $pageSize = 20;
        }
        try{
	    $dblsObj = new DealerBailLogService();
            $logs = $dblsObj->selectDealerLog($where,$page,$pageSize);
            $nums = $dblsObj->countDealerLog($where);
        }catch (\Exception $e){
            throw new InvalidException(array('code' => 10012, 'message' => $this->exceptionCode[10012]));
        }
        $bail = new Bail();
        $bail->code ='000000';
        $bail->message='success';
        $bail->data = array("logs"=>json_encode($logs),'nums'=>$nums['nums'],'curr_page'=>$page,'totle_page'=>ceil($nums['nums'] / $pageSize));  //array('1'=>$where);
        return $bail;
    }    
}
